package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.properties.HuaWeiIotConfigProperties;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import com.zzyl.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.stream.Collectors;

/**
 * 设备管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-05-25
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 查询设备管理
     * 
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备管理列表
     * 
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     * 
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备管理
     * 
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备管理
     * 
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备管理信息
     * 
     * @param id 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private IoTDAClient client;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 从物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        //对接华为云,获取餐品列表
        ListProductsResponse response = client.listProducts(new ListProductsRequest());
        if (response==null || response.getHttpStatusCode()!=200){
            throw new BaseException("同步列表异常");
        }

        //餐品列表转为json字符串,存入缓存
        List<ProductSummary> products = response.getProducts();
        redisTemplate.opsForValue().set(CacheConstants.HUA_WEI_IOT_LIST_KEY, JSONUtil.toJsonStr(products));
    }


    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> findAllProduct() {
        //1.从缓存中获取同步的产品数据
        String result = redisTemplate.opsForValue().get(CacheConstants.HUA_WEI_IOT_LIST_KEY);
        //2.将获取到的数据解析为产品类型
        List<ProductSummary> resultList = JSONUtil.toList(result, ProductSummary.class);
        //3.将产品转为ProductVo类型
        List<ProductVo> productVoList = resultList.stream().map(x -> {
            ProductVo productVo = new ProductVo();
            productVo.setProductKey(x.getProductId());
            productVo.setProductName(x.getName());
            return productVo;
        }).collect(Collectors.toList());
        //4.返回数据
        return productVoList;
    }


    /**
     * 注册设备
     *
     * @param dto
     */
    @Override
    public void register(DeviceDto dto) {
        //1.根据设备名称查询是否重复
        Long countDevice = this.lambdaQuery().eq(Device::getDeviceName, dto.getRegisterDeviceRequest().getDeviceName()).count();
        if(countDevice>0){
            throw new BaseException("存在相同的的设备名称,出问题");
        }
        //2.根据设备标识查询是否重复
        //2.1使用雪花算法生成唯一值
        String nodeId = IdUtil.getSnowflakeNextIdStr();
        Long countNodeId = this.lambdaQuery().eq(Device::getNodeId, nodeId).count();
        if (countNodeId>0){
            throw new BaseException("存在相同的设备标识,出现问题");
        }
        //3.根据同一位置查询是否太重复
        Long countLocation = this.lambdaQuery()
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getPhysicalLocationType, dto.getPhysicalLocationType())
                .count();
        if (countLocation>0){
            throw new BaseException("存在同一位置重复的情况");
        }
        //4.注册设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();

        body.setNodeId(nodeId);//设备标识码
        body.setProductId(dto.getProductKey());//设备关联的产品ID
        body.setDeviceName(dto.getDeviceName());//设备的名称
        String description = dto.getRegisterDeviceRequest().getNickname();
        body.setDescription(description);//设备描述
        String secret = IdUtil.fastSimpleUUID();//产品密钥
        AuthInfo authInfoBody = new AuthInfo();
        authInfoBody.setSecret(secret);//产品密钥添加到AuthInfo实例
        body.setAuthInfo(authInfoBody);//设置产品密钥

        request.setBody(body);

        //发起注册设备请求,得到响应结果
        AddDeviceResponse response = client.addDevice(request);
        if (response==null || response.getHttpStatusCode()!=201){
            throw new BaseException("调用IOT接口注册设备失败");
        }
        //5.解析响应结果
        String iotId = response.getDeviceId();//物联网设备唯一ID

        //6.新增设备到表中
        Device device = new Device();
        BeanUtils.copyProperties(dto,device);
        device.setIotId(iotId);
        device.setNodeId(nodeId);
        device.setSecret(secret);
        device.setDeviceDescription(description);
        device.setNickname(description);


        device.setProductKey(dto.getProductKey());
        //根据产品id到redis中查询产品名称
        String productName = getProductName(dto.getProductKey());
        device.setProductName(productName);

        boolean result = this.save(device);
        if(!result){
            throw new BaseException("新增设备失败");
        }
    }

    /**
     * 根据产品id获取产品名称
     * @param productKey
     */
    private String getProductName(String productKey) {
        //1.查询redis产品列表的JSON字符串
        String productListJSON = redisTemplate.opsForValue().get(CacheConstants.HUA_WEI_IOT_LIST_KEY);
        //2.解析JSON字符串
        List<ProductSummary> productList = JSONUtil.toList(productListJSON, ProductSummary.class);
        //3.筛选出列表中同名产品id的产品对象
        ProductSummary product = productList.stream().filter(x -> x.getProductId().equals(productKey)).findFirst().get();
        //4.获取该产品对象的产品名
        if (product!=null){
            return product.getName();
        }
        return null;
    }

    @Autowired
    private ISysUserService userService;
    @Autowired
    private HuaWeiIotConfigProperties huaWeiIotConfigProperties;

    /**
     * 查询设备详细信息
     *
     * @param dto
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(DeviceDto dto) {
        //1.判断表中数据是否存在
        String iotId = dto.getIotId();
        Device device = this.lambdaQuery().eq(Device::getIotId, iotId).one();
        if (device==null){
            throw new BaseException("表中数据不存在");
        }
        //2.拷贝
        DeviceDetailVo deviceDetailVo = new DeviceDetailVo();
        BeanUtils.copyProperties(device,deviceDetailVo);

        deviceDetailVo.setDeviceSecret(device.getSecret());
        deviceDetailVo.setBindingLocation(Long.valueOf(device.getBindingLocation()));

        deviceDetailVo.setGmtCreate(device.getCreateTime());
        deviceDetailVo.setRegion(huaWeiIotConfigProperties.getRegionId());
        SysUser sysUser = userService.selectUserById(Long.valueOf(device.getCreateBy()));
        String creator = sysUser.getUserName();
        deviceDetailVo.setCreator(creator);


        //3.查询华为云IOT数据
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);

        ShowDeviceResponse response = client.showDevice(request);
        if (response==null || response.getHttpStatusCode()!=200){
            throw new BaseException("查询失败");
        }

        //4.补充数据
        deviceDetailVo.setDeviceStatus(response.getStatus());
        deviceDetailVo.setDeviceStatus(response.getStatus());
        String activeTime = response.getActiveTime();
        if(StringUtils.isNotBlank(activeTime)){
            //转换为东八区时间
            LocalDateTime gmActive = OffsetDateTime.parse(activeTime).atZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
            deviceDetailVo.setGmtActive(gmActive);
        }
        //5.返回数据
        return deviceDetailVo;
    }


    /**
     * 查看指定产品的已发布物模型中的功能定义详情
     *
     * @param productKey
     * @return
     */
    @Override
    public JSONObject queryProductModelInfo(String productKey) {
        //1.直接查看华为云IOT中的数据
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);

        ShowProductResponse response = client.showProduct(request);
        if (response==null || response.getHttpStatusCode()!=200){
            throw new BaseException("查看指定产品的已发布物模型中的功能定义详情失败");
        }

        //2.解析数据
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if (CollectionUtils.isEmpty(serviceCapabilities)){
            throw new BaseException("获取数据失败");
        }

        ServiceCapability serviceCapability = serviceCapabilities.get(0);

        //3.转数据,返回数据
        JSONObject jsonObject = JSONUtil.parseObj(serviceCapability);

        return jsonObject;
    }


    /**
     * 查询指定设备的物模型运行状态
     *
     * @param deviceName
     * @return
     */
    @Override
    public Map<String, Object> queryDevicePropertyStatus(String deviceName) {
        //1.根据参数判断表中数据是否存在
        Device device = this.lambdaQuery().eq(Device::getDeviceName, deviceName).one();
        if (device==null){
            throw new BaseException("表中数据不存在");
        }
        String iotId = device.getIotId();
        //2.调用华为云IOT查询影子设备
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);


        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response==null || response.getHttpStatusCode()!=200){
            throw new BaseException("调用华为云IOT查询影子设备失败");
        }
        //3.解析数据并进行封装
        List<DeviceShadowData> shadowDataList = response.getShadow();
        if (CollectionUtils.isEmpty(shadowDataList)){
            throw new BaseException("调用华为云IOT查询影子设备为空");
        }

        DeviceShadowData shadowData = shadowDataList.get(0);
        DeviceShadowProperties reported = shadowData.getReported();

        String eventTimeStr = reported.getEventTime();
        LocalDateTime eventTime = OffsetDateTime.parse(eventTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"))
                .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        JSONObject jsonObject = JSONUtil.parseObj(reported.getProperties());
        List<Map<String,Object>> mapList = new ArrayList<>();

        jsonObject.forEach((k,v)->{
            HashMap<String, Object> propertyMap = new HashMap<>();
            propertyMap.put("identifier",k);
            propertyMap.put("name",k);
            propertyMap.put("value",v);
            propertyMap.put("time",eventTime);
            mapList.add(propertyMap);
        });
        //4.返回map类型数据
        Map<String,Object> resultMap = new HashMap<>();
        Map<String,Object> propertyStatusInfoMap = new HashMap<>();
        propertyStatusInfoMap.put("propertyStatusInfo",mapList);
        resultMap.put("list",propertyStatusInfoMap);

        return resultMap;
    }

    /**
     * 修改设备备注名称
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDeviceRemark(DeviceDto dto) {
        //1.判断表中是否存在DeviceDto数据
        Device device = this.lambdaQuery().eq(Device::getId, dto.getId()).one();
        if (device==null){
            throw new BaseException("表中没有该设备数据,为空");
        }
        //2.补全基础属性
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        String iotId = device.getIotId();//物联网设备id
        request.setDeviceId(iotId);

        UpdateDevice body = new UpdateDevice();
        AuthInfoWithoutSecret authInfoBody = new AuthInfoWithoutSecret();
        authInfoBody.setSecureAccess(true);

        body.setDeviceName(device.getDeviceName());
        body.setDescription(device.getDeviceDescription());
        body.setAuthInfo(authInfoBody);

        request.setBody(body);

        //3.调用阿里云IOTDA的更新设备方法
        UpdateDeviceResponse response = client.updateDevice(request);//调用华为云IOTDA修改设备方法
        if (response==null || response.getHttpStatusCode()!=200){
            throw new BaseException("更新设备失败");
        }

        //4.更新表中数据
        Device device1 = new Device();
        BeanUtils.copyProperties(dto,device1);
        device1.setNickname(dto.getRegisterDeviceRequest().getNickname());
        boolean result = this.updateById(device1);
        if (!result){
            throw new BaseException("修改表中数据失败");
        }
    }

    @Autowired
    private IDeviceDataService deviceDataService;

    /**
     * 删除设备
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDevice(DeviceDto dto) {
        //1.判断设备是否存在
        Device device = this.lambdaQuery().eq(Device::getIotId, dto.getIotId())
                .eq(Device::getProductKey,dto.getProductKey())
                .one();
        if (device==null){
            throw new BaseException("设备不存在");
        }

        String iotId = dto.getIotId();
        //2.调用华为云删除方法
        DeleteDeviceRequest request = new DeleteDeviceRequest();

        request.withDeviceId(iotId);

        DeleteDeviceResponse response = client.deleteDevice(request);
        if (response==null || response.getHttpStatusCode()!=200){
            throw new BaseException("删除设备失败1");
        }

        //3.删除设备及关联表中数据
        //3.1删除关联表中数据
        List<DeviceData> deviceDataList = deviceDataService.lambdaQuery().eq(DeviceData::getIotId, iotId).list();

        boolean result1 = deviceDataService.removeBatchByIds(deviceDataList);
        if (!result1){
            throw new BaseException("删除设备关联表中数据失败");
        }

        //3.2删除设备表中数据
        boolean result = this.removeById(device);
        if (!result){
            throw new BaseException("删除设备失败2");
        }
    }
}
